/*
 * v1.1 by tonydon site:txdnet.cn
 * netbeansIDE 7.1
 */
package cn.txdnet.txcms.auth;
import cn.txdnet.txweb.utils.SessionUtil;
import cn.txdnet.txweb.utils.WebUtil;
import java.io.IOException;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import txdnet.util.Logger;
import txdnet.util.StaticMark;
/**
 * @author txdnet
 *
 */
public class AdminSessionFilter  implements Filter {
    private FilterConfig filterConfig = null;
    private String errRedirect = null;
   

    public AdminSessionFilter() {
    } 

    private boolean doBeforeProcessing(ServletRequest request, ServletResponse response)
	throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse) response;
        Object obj = SessionUtil.getManager(req);
        if(obj==null){
            return false;
        }

       return true;
    } 

    @Override
    public void doFilter(ServletRequest request, ServletResponse response,
                         FilterChain chain)
	throws IOException, ServletException {


	if(!doBeforeProcessing(request, response)){
		HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse) response;
            res.sendRedirect(errRedirect);
            return;
        }
	
	Throwable problem = null;
	try {
	    chain.doFilter(request, response);
	}
	catch(Throwable t) {
	    // If an exception is thrown somewhere down the filter chain,
	    // we still want to execute our after processing, and then
	    // rethrow the problem after that.
	    problem = t;
	    Logger.error(AdminSessionFilter.class, t.toString());
	}

	// If there was a problem, we want to rethrow it if it is
	// a known type, otherwise log it.
	if (problem != null) {
	    if (problem instanceof ServletException) throw (ServletException)problem;
	    if (problem instanceof IOException) throw (IOException)problem;
	    sendProcessingError(problem, response);
	}
    }
    
    /**
     * Return the filter configuration object for this filter.
     */
    public FilterConfig getFilterConfig() {
	return (this.filterConfig);
    }

    /**
     * Set the filter configuration object for this filter.
     *
     * @param filterConfig The filter configuration object
     */
    public void setFilterConfig(FilterConfig filterConfig) {
	this.filterConfig = filterConfig;
    }

    /**
     * Destroy method for this filter 
     */
    @Override
    public void destroy() { 
    }

    /**
     * Init method for this filter 
     */
    @Override
    public void init(FilterConfig filterConfig) { 
	this.filterConfig = filterConfig;
	if (filterConfig != null) {
	    this.errRedirect = this.getFilterConfig().getInitParameter("err-redirect");
            if(this.errRedirect==null || this.errRedirect.length()==0){
                this.errRedirect = WebUtil.WEB_CTX_PATH.concat(StaticMark.STR_SLASH);
            }
	}
    }

    /**
     * Return a String representation of this object.
     */
    @Override
    public String toString() {
	if (filterConfig == null) return ("AdminSessionFilter()");
	StringBuilder sb = new StringBuilder("AdminSessionFilter(");
	sb.append(filterConfig);
	sb.append(")");
	return (sb.toString());
    }

    private void sendProcessingError(Throwable t, ServletResponse response) {
	String stackTrace = getStackTrace(t); 

	if(stackTrace != null && !stackTrace.isEmpty()) {
	    try {
		response.setContentType("text/html");
		PrintStream ps = new PrintStream(response.getOutputStream());
		PrintWriter pw = new PrintWriter(ps); 
		pw.print(stackTrace); 
		pw.close();
		ps.close();
		response.getOutputStream().close();
	    }
	    catch(Exception ex) {}
	}
	else {
	    try {
		PrintStream ps = new PrintStream(response.getOutputStream());
		t.printStackTrace(ps);
		ps.close();
		response.getOutputStream().close();
                 
	    }
	    catch(Exception ex) {}
	}
    }

    public static String getStackTrace(Throwable t) {
	String stackTrace = null;
	try {
	    StringWriter sw = new StringWriter();
	    PrintWriter pw = new PrintWriter(sw);
	    t.printStackTrace(pw);
	    pw.close();
	    sw.close();
	    stackTrace = sw.getBuffer().toString();
            Logger.error(AdminSessionFilter.class, stackTrace);
	}
	catch(Exception ex) {}
	return stackTrace;
    }
}
